import {Button, Input, Pressable, Text, View, useTheme} from 'native-base';
import {SafeAreaView} from 'react-native-safe-area-context';
import React, {useCallback, useState} from 'react';
import Icon from '@/components/Icon';
import {delSearchHistory, getSearchHistory, saveSearchHistory} from '@/utils';
import {useFocusEffect} from '@react-navigation/native';
import {TouchableHighlight} from 'react-native';
import History from './history';
import Detail from './detail';

export default function () {
  const theme = useTheme();
  const [searchName, setSearchName] = useState('');
  const [searchHistory, setSearchHistory] = useState<Array<any>>([]);
  const [loading, setLoading] = useState(false);
  const [isSearch, setIsSearch] = useState(false);
  const [searchData, setSearchData] = useState([]);

  const search = useCallback(() => {
    setSearchHistory((state: any) => {
      const newArr: any[] = [];
      state.map((item: any) => {
        if (item && item.trim()) {
          newArr.push(item);
        }
      });
      newArr.push(searchName);
      setIsSearch(true);
      return newArr;
    });
    if (searchHistory && searchHistory.length > 0) {
      saveSearchHistory(searchHistory);
    }
  }, [searchName, searchHistory]);
  const useSearchHis = useCallback(
    (text: string) => {
      setSearchName(text);
    },
    [searchName],
  );
  const delHis = useCallback(async () => {
    await delSearchHistory();
    setSearchHistory([]);
  }, []);
  const onSearchInput = useCallback((text: string) => {
    setSearchName(text);
    if (!text) {
      setIsSearch(false);
    }
  }, []);
  const foucusFn = useCallback(() => {
    (async () => {
      const shis = await getSearchHistory();
      if (shis && shis.length > 0) {
        setSearchHistory(shis);
      }
    })();
  }, []);
  useFocusEffect(foucusFn);
  return (
    <SafeAreaView>
      <View px={'2'}>
        <View
          px={'10'}
          py={'4'}
          borderBottomColor={'gray.300'}
          borderBottomWidth={'0.5'}
          flexDirection={'row'}>
          <Input
            flex={9}
            autoFocus={true}
            rounded={'xl'}
            value={searchName}
            onChangeText={text => onSearchInput(text)}
            placeholder="请输入搜索内容"
            leftElement={<Icon pl={'2'} iconName={'\ue645'}></Icon>}
            rightElement={
              <Button size={'sm'} rounded={'xl'} onPress={search}>
                搜索
              </Button>
            }
          />
        </View>
        {!(isSearch && searchName && searchName.trim()) ? (
          <History
            searchHistory={searchHistory}
            onSearchHis={useSearchHis}
            ondelHis={delHis}
          />
        ) : (
          <Detail data={searchData} loading={loading}></Detail>
        )}
      </View>
    </SafeAreaView>
  );
}
